package com.djmw.mouse.web.hr;

import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import javax.validation.Validator;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.djmw.mouse.entity.Company;
import com.djmw.mouse.entity.Department;
import com.djmw.mouse.entity.HrUser;
import com.djmw.mouse.service.DepartmentService;
import com.djmw.mouse.service.account.HrAccountService;
import com.djmw.mouse.service.account.ShiroDbRealm.ShiroUser;
import com.google.common.collect.Maps;

/**
 * 部门管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /hr/option/department <br>
 * Create page : GET /hr/option/department/create <br>
 * Create action : POST /hr/option/department/create <br>
 * Update page : GET /hr/option/department/update/{id} <br>
 * Update action : POST /hr/option/department/update <br>
 * Delete action : GET /hr/option/department/delete/{id} <br>
 * 
 * @author michael
 */

@Controller
@RequestMapping(value = "/hr/option/department")
public class DepartmentController {

    private static final int PAGE_SIZE = 20;

    private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
    static {
        sortTypes.put("auto", "自动");
        sortTypes.put("name", "部门名称");
    }

    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private HrAccountService hrAccountService;
    @Autowired
    private Validator validator;

    @RequestMapping(value = "")
    public String list(@RequestParam(value = "sortType", defaultValue = "auto") String sortType,
            @RequestParam(value = "page", defaultValue = "1") int pageNumber, Model model, ServletRequest request) {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page<Department> departments = departmentService.getCompanyDepartment(getCurrentCompany().getId(),
                searchParams, pageNumber, PAGE_SIZE, sortType);

        model.addAttribute("departments", departments);
        model.addAttribute("sortType", sortType);
        model.addAttribute("sortTypes", sortTypes);
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));

        return "hr/option/department-list";
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String createForm(Model model) {
        model.addAttribute("department", new Department());
        model.addAttribute("companyId", getCurrentCompany().getId());
        model.addAttribute("action", "create");
        return "hr/option/department-form";
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(@Valid Department department, Long companyId, RedirectAttributes redirectAttributes) {
        Company company = new Company(companyId);
        department.setCompany(company);
        departmentService.saveDepartment(department);
        redirectAttributes.addFlashAttribute("message", "创建部门成功");
        return "redirect:/hr/option/department/";
    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("department", departmentService.getDepartment(id));
        model.addAttribute("companyId", getCurrentCompany().getId());
        model.addAttribute("action", "update");
        return "hr/option/department-form";
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute("preloadDepartment") Department department, Long companyId,
            RedirectAttributes redirectAttributes) {
        Company company = new Company(companyId);
        department.setCompany(company);
        departmentService.saveDepartment(department);
        redirectAttributes.addFlashAttribute("message", "更新部门成功");
        return "redirect:/hr/option/department/";
    }

    @RequestMapping(value = "delete/{id}")
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        departmentService.deleteDepartment(id);
        redirectAttributes.addFlashAttribute("message", "删除部门成功");
        return "redirect:/hr/option/department/";
    }

	        /**
     * 使用@ModelAttribute, 实现Struts2
     * Preparable二次部分绑定的效果,先根据form的id从数据库查出Company对象,再把Form提交的内容绑定到该对象上。
     * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
     */
    @ModelAttribute("preloadDepartment")
    public Department getDepartment(@RequestParam(value = "id", required = false) Long id) {
        if (id != null) {
            return departmentService.getDepartment(id);
        }
        return null;
    }

    public Company getCurrentCompany() {
        ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        HrUser hrUser = (HrUser) user.getUser();
        Company company = hrUser.getCompany();
        return company;
    }
}
